#pragma once

#include "Connection.hpp"
#include "IOService.hpp"
#include "PipeAgreement.hpp"



class Pipeer : public Connection
{
public:
    Pipeer(int rfd, Reactor *owner)
        : Connection(owner),
          _rfd(rfd)
    {
    }

    void Accept(const PipeAgreement& agreement)
    {
        FdSetNonBlock(agreement.Fd()); // 把fd设置为非阻塞

        LOG(LogLevel::DEBUG) << "成功获取新连接,fd: " <<agreement.Fd();

        auto sock = make_shared<IOService>(Owner(), agreement.DistPort(), agreement.DistIp(),agreement.Fd());

        // 调用Reactor的成员函数InsertConnection
        Owner()->InsetConnection(agreement.Fd(), sock);
        Owner()->PushTimestamp(agreement.Fd(), sock);
    }
    void thread_exit()
    {
        Owner()->Stop();
    }

    virtual int Fd()
    {
        return _rfd;
    }
    virtual void Recver() // 从ListrnSocket中获取新连接
    {
        // 读取管道中的数据
        PipeAgreement agreement;
        int n = read(_rfd, &agreement, sizeof(agreement));
        if (n > 0)
        {
            if (n < sizeof(agreement))
            {
                LOG(LogLevel::WARNING) << "从管道到的数据字节不足,管道rfd: " << _rfd;
            }
            // 根据操作码进行操作
            int code=agreement.Code();

            LOG(LogLevel::WARNING) << "管道rfd: " << _rfd<<"成功获取操作码："<<code;
            switch (code)
            {
            case Code_Type::ACCEPT:
                Accept(agreement);
                break;
            case Code_Type::STOP:
                thread_exit();
                break;
            default:
                LOG(LogLevel::WARNING) << "非法操作码code: " << code << ",管道rfd: " << _rfd;
                break;
            }
        }
        else if (n == 0)
        {
            LOG(LogLevel::WARNING) << "管道损坏,管道rfd: " << _rfd;
            Excepter();
            return;
        }
        else
        {
            LOG(LogLevel::WARNING) << "read error,管道rfd: " << _rfd;
            Excepter();
            return;
        }
    }

    virtual void Sender()
    {
    }
    virtual void Excepter()
    {
        char error_buf[defalut_error_buff_size];
        strerror_r(errno, error_buf, sizeof(error_buf));
        LOG(LogLevel::WARNING) << "error: " << error_buf;

        // 调用Reactor的成员函数DeleteConnection
        Owner()->DleteConnection(Fd());
    }
    ~Pipeer()
    {
        close(_rfd);
    }

private:
    int _rfd; // 管道写端fd
};
